﻿using System;
using System.Collections.Generic;
using System.Linq;
using Aden.Model.Common;
using Aden.Util.Common;
using Aden.Model.Stock;
using Aden.Model.SOMastData;
using NPOI.SS.Formula.Functions;

namespace Aden.DAL.StockData
{
    public class POStockin : Stockin
    {
        private Purchase.PurchaseOrderFactory pofactory = new Purchase.PurchaseOrderFactory();

        public POStockin(string appGuid, string costCenterCode, string orderDate, string createUser)
            :base(appGuid, costCenterCode, "POReceipt", orderDate, createUser) {}

        public override List<Dictionary<string,object>> GetItems(StockParam param)  // Dictionary<string, string> dicparam
        {
            try
            {               
              
                    List < Dictionary<string, object> > GetPO
                    = pofactory.GetPO(!string.IsNullOrWhiteSpace(param.headGuid) ? param.headGuid : null, CostCenterCode,
                        !string.IsNullOrWhiteSpace(param.supplierCode) ? param.supplierCode : null, null).Select(q =>
                        {
                            Dictionary<string, object> dic = new Dictionary<string, object>();
                            //dic.Add("orderGUID", q.headGuid);
                            dic.Add("orderLineGUID", q.guid);
                            dic.Add("itemCode", q.itemCode);
                            dic.Add("itemName", q.itemName);
                            //dic.Add("itemCost", q.purchasePrice);
                            dic.Add("uom", q.stockUnit);
                            dic.Add("purPrice", q.purchasePrice);
                            dic.Add("remark", q.remark);
                            //dic.Add("supplierCode", q.supplierCode);
                            dic.Add("purStk_Conversion", q.purStk_Conversion);
                            dic.Add("qty", q.qty + q.adjQty);
                            return dic;
                        }).ToList();

                List<Dictionary<string, object>> GetPurchaseItems
                    = pofactory.GetPurchaseItems(CostCenterCode, OrderDate);

                if (!GetPO.Any() || !GetPurchaseItems.Any()) return null;

                List<Dictionary<string, object>> result = GetPO.GroupJoin(GetPurchaseItems, a => a["itemCode"], b => b["itemCode"],
                    (a, b) =>
                    {
                        a["itemName"] = b.FirstOrDefault()["itemName_ZH"].ToString();
                        return a;
                    }).ToList();

                return result;
            }
            catch(Exception e)
            {
                throw e;
            }
        }


       
        public override List<Dictionary<string, object>> GetDates()
        {
            //DateTime? date1 = stocktrans.GetLastOutDate();

            //DateTime? date2 = stocktrans.GetMinPriceListDate(CostCenterCode);

            // DateTime endDate = new AppProcess.AppProcessFactory().GetEndTime("40820A3F-3A22-4FC8-9F7B-85255015AA50", CostCenterCode, null);
            // PO getdate
            //List<Dictionary<string, object>> dic =  pofactory.OpenPODates(CostCenterCode,endTime).ToList();
            List<Dictionary<string, object>> dic = pofactory.OpenPODates(CostCenterCode, DateTime.Now).ToList();

            //if (date1 == null && date2 ==null)
            //     return dic;

            // DateTime d1 = date1 == null ? DateTime.Parse("2000-01-01") : (DateTime)date1;
            // DateTime d2 = date2 == null ? DateTime.Parse("2000-01-01") : (DateTime)date2;
            // 最后出库日期 - 今天
            //return dic.Where(q=>DateTime.Parse(q["date"].ToStringTrim()) > (DateTime.Compare(d1,d2)>0 ? d1 : d2)
            //     && q["poType"].ToStringTrim().ToLower()!="addition" && q["poType"].ToStringTrim().ToLower() != "nofood" ? DateTime.Parse(q["date"].ToStringTrim()) <= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")) : true) // 正常单<=今天/补单和非食品单不限
            //    .OrderByDescending(q=> q["poType"].ToStringTrim()).ThenBy(q => DateTime.Parse(q["date"].ToStringTrim())).ToList();
            return dic.Where(q => DateTime.Parse(q["date"].ToStringTrim()) <= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"))) // 正常单/补单和非食品单<=今天
                .OrderByDescending(q => q["poType"].ToStringTrim()).ThenBy(q => DateTime.Parse(q["date"].ToStringTrim())).ToList();
        }

        public override Dictionary<string, object> ShowComponents()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
          
            dic["Item"] = new Dictionary<string, object>() { { "change", false } };
            dic["ItemDesc"] = new Dictionary<string, object>() { { "visible", false } };
            dic["Price"] = new Dictionary<string, object>() { { "visible", true }, { "change", false } };
            dic["QrderQty"] = new Dictionary<string, object>() { { "visible", true } };
            dic["StockQty"] = new Dictionary<string, object>() { { "visible", false } };
            dic["ToCostCenter"] = new Dictionary<string, object>() { { "visible", false } };
            dic["BusinessType"] = new Dictionary<string, object>() { { "visible", false }, { "change", false } };
            dic["InQty"] = new Dictionary<string, object>() { { "visible", false } };
            dic["Remark"] = new Dictionary<string, object>() { { "visible", true }, { "change", true } };
            return dic;
        }

        public override Dictionary<string, object> save(StockParam param) // Dictionary<string,string> param, List<TransData> data
        {
            try
            {
                string orderGuid = param.headGuid;
                if(string.IsNullOrWhiteSpace(orderGuid))
                    throw new Exception("No PO to receive");
                // purchase Price => Stock Price, Save Stock Price to tblTransData
                param.data = param.data.Select(dr =>
                {
                    dr.supplierCode = param.supplierCode;
                    dr.itemPrice = dr.purPrice * dr.purStk_Conversion;
                    dr.qty = dr.purQty;
                    return dr;
                }).ToList();
               
                base.save(param.data, new List<SQL> {
                    new SQL
                    {
                        sqls = pofactory.SavePOStockinSQL(orderGuid, param.supplierCode),
                        error = "This PO has been stockin",
                        ExeRecordCount = (int)param.data.Count
                    }
                });
                return null;
            }
            catch(Exception e)
            {
                throw e;
            }
        }
    }
}
